/**
 * 用户认证模块
 */

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5001/api';

export interface User {
  id: number;
  email: string;
  username: string;
  created_at: string;
  roles?: string[];
}

export interface AuthResponse {
  success: boolean;
  message?: string;
  user?: User;
  access_token?: string;
  refresh_token?: string;
  error?: string;
}

/**
 * 用户注册
 */
export async function register(email: string, password: string, username?: string): Promise<AuthResponse> {
  try {
    const response = await fetch(`${API_BASE}/auth/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email, password, username }),
    });

    const data = await response.json();
    
    if (response.ok && data.access_token) {
      // 保存 token
      localStorage.setItem('access_token', data.access_token);
      localStorage.setItem('refresh_token', data.refresh_token);
      localStorage.setItem('user', JSON.stringify(data.user));
    }
    
    return data;
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : '注册失败',
    };
  }
}

/**
 * 用户登录
 */
export async function login(email: string, password: string): Promise<AuthResponse> {
  try {
    const response = await fetch(`${API_BASE}/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email, password }),
    });

    const data = await response.json();
    
    if (response.ok && data.access_token) {
      // 保存 token
      localStorage.setItem('access_token', data.access_token);
      localStorage.setItem('refresh_token', data.refresh_token);
      localStorage.setItem('user', JSON.stringify(data.user));
    }
    
    return data;
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : '登录失败',
    };
  }
}

/**
 * 用户登出
 */
export async function logout(): Promise<void> {
  try {
    const token = localStorage.getItem('access_token');
    
    if (token) {
      await fetch(`${API_BASE}/auth/logout`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
    }
  } catch (error) {
    console.error('Logout error:', error);
  } finally {
    // 清除本地存储
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('user');
  }
}

/**
 * 获取当前用户 - 优先从本地存储读取
 */
export async function getCurrentUser(): Promise<User | null> {
  try {
    // 首先检查本地存储
    const storedUser = getStoredUser();
    if (storedUser) {
      console.log('Using stored user:', storedUser.email);
      return storedUser;
    }
    
    // 如果没有本地用户信息但有 token，则从服务器获取
    const token = localStorage.getItem('access_token');
    if (!token) {
      console.log('No token found');
      return null;
    }

    console.log('Fetching user from server...');
    const response = await fetch(`${API_BASE}/auth/me`, {
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });

    if (!response.ok) {
      console.warn('Failed to get user, status:', response.status);
      // 如果未授权，尝试刷新一次再重试
      if (response.status === 401) {
        const refreshed = await refreshToken();
        if (refreshed) {
          const newToken = localStorage.getItem('access_token');
          if (newToken) {
            const retry = await fetch(`${API_BASE}/auth/me`, {
              headers: { 'Authorization': `Bearer ${newToken}` },
            });
            if (retry.ok) {
              const retryData = await retry.json();
              localStorage.setItem('user', JSON.stringify(retryData.user));
              return retryData.user;
            }
          }
      }
      }
      // 刷新失败或其他错误，清除本地存储
      localStorage.removeItem('access_token');
      localStorage.removeItem('refresh_token');
      localStorage.removeItem('user');
      return null;
    }

    const data = await response.json();
    // 更新本地存储的用户信息
    localStorage.setItem('user', JSON.stringify(data.user));
    console.log('User fetched successfully:', data.user.email);
    return data.user;
  } catch (error) {
    console.error('Get current user error:', error);
    return null;
  }
}

/**
 * 刷新访问令牌
 */
export async function refreshToken(): Promise<boolean> {
  try {
    const refresh = localStorage.getItem('refresh_token');
    
    if (!refresh) {
      console.warn('No refresh token found');
      return false;
    }

    const response = await fetch(`${API_BASE}/auth/refresh`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${refresh}`,
      },
    });

    if (!response.ok) {
      console.warn('Failed to refresh token, clearing local storage');
      // 刷新失败，清除所有认证信息
      localStorage.removeItem('access_token');
      localStorage.removeItem('refresh_token');
      localStorage.removeItem('user');
      return false;
    }

    const data = await response.json();
    if (data.access_token) {
      localStorage.setItem('access_token', data.access_token);
      console.log('Token refreshed successfully');
      return true;
    }
    
    return false;
  } catch (error) {
    console.error('Refresh token error:', error);
    // 出错时清除认证信息
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('user');
    return false;
  }
}

/**
 * 检查是否已登录
 */
export function isAuthenticated(): boolean {
  return !!localStorage.getItem('access_token');
}

/**
 * 获取存储的用户信息
 */
export function getStoredUser(): User | null {
  try {
    const userStr = localStorage.getItem('user');
    return userStr ? JSON.parse(userStr) : null;
  } catch {
    return null;
  }
}

/**
 * 获取访问令牌
 */
export function getAccessToken(): string | null {
  return localStorage.getItem('access_token');
}

